<template>
  <div class="auth-container">
    <!-- 自定义标题栏 (仅在Electron环境下显示) -->
    <TitleBar v-if="isElectron" />

    <!-- 背景装饰 -->
    <div class="auth-background">
      <div class="bg-pattern"></div>
      <div class="bg-gradient"></div>
    </div>

    <div class="auth-content">
      <!-- 品牌展示区 -->
      <div class="brand-section">
        <div class="brand-content">
          <div class="brand-logo">
            <el-icon class="logo-icon"><Folder /></el-icon>
            <h1 class="logo-text">RickPan</h1>
          </div>

          <div class="brand-description">
            <h2>企业级文件管理平台</h2>
            <p>安全、高效、智能的云端文件存储与协作解决方案</p>

            <div class="feature-highlights">
              <div class="feature-item">
                <el-icon><Upload /></el-icon>
                <span>云端存储</span>
              </div>
              <div class="feature-item">
                <el-icon><Share /></el-icon>
                <span>团队协作</span>
              </div>
              <div class="feature-item">
                <el-icon><Lock /></el-icon>
                <span>安全加密</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 登录表单区 -->
      <div class="form-section">
        <div class="form-container theme-card">
          <!-- 主题切换按钮 -->
          <div class="theme-toggle">
            <el-tooltip :content="themeStore.isDark ? '切换到日间模式' : '切换到夜间模式'" placement="left">
              <el-button
                text
                circle
                @click="themeStore.toggleTheme()"
                class="theme-toggle-btn"
              >
                <el-icon>
                  <Sunny v-if="themeStore.isDark" />
                  <Moon v-else />
                </el-icon>
              </el-button>
            </el-tooltip>
          </div>

          <div class="form-header">
            <h2>欢迎回来</h2>
            <p>登录您的RickPan账户，继续您的工作</p>
          </div>

          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            size="large"
            class="auth-form"
            @submit.prevent="handleSubmit"
          >
            <el-form-item prop="username">
              <div class="input-wrapper">
                <label class="input-label">用户名或邮箱</label>
                <el-input
                  v-model="form.username"
                  placeholder="用户名：3-20字符，字母数字下划线"
                  :prefix-icon="User"
                  clearable
                  class="theme-input"
                />
              </div>
            </el-form-item>

            <el-form-item prop="password">
              <div class="input-wrapper">
                <label class="input-label">密码</label>
                <el-input
                  v-model="form.password"
                  type="password"
                  placeholder="密码：6-20字符，必须包含字母和数字"
                  :prefix-icon="Lock"
                  show-password
                  clearable
                  class="theme-input"
                  @keyup.enter="handleSubmit"
                />
              </div>
            </el-form-item>

            <el-form-item prop="captcha">
              <div class="input-wrapper">
                <label class="input-label">验证码</label>
                <CaptchaCode
                  v-model="form.captcha"
                  placeholder="请输入验证码"
                  ref="captchaRef"
                  @change="handleCaptchaChange"
                  @captcha-id-change="handleCaptchaIdChange"
                  @enter="handleSubmit"
                />
              </div>
            </el-form-item>

            <el-form-item>
              <div class="form-options">
                <el-checkbox v-model="rememberMe" class="remember-checkbox">
                  记住我
                </el-checkbox>
                <router-link to="/auth/forgot-password" class="forgot-link theme-link">
                  忘记密码？
                </router-link>
              </div>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                size="large"
                :loading="authStore.loading"
                @click="handleSubmit"
                class="submit-btn theme-button-primary"
              >
                <span v-if="!authStore.loading">
                  <el-icon><Right /></el-icon>
                  立即登录
                </span>
                <span v-else>
                  登录中...
                </span>
              </el-button>
            </el-form-item>
          </el-form>

          <div class="form-footer">
            <div class="divider">
              <span>或</span>
            </div>

            <p class="register-prompt">
              还没有账户？
              <router-link to="/auth/register" class="register-link theme-link">
                立即注册
              </router-link>
            </p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import {
  User,
  Lock,
  Folder,
  Upload,
  Share,
  Right,
  Sunny,
  Moon
} from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { useThemeStore } from '@/stores/theme'
import TitleBar from '@/components/electron/TitleBar.vue'
import CaptchaCode from '@/components/auth/CaptchaCode.vue'
import type { LoginRequest } from '@/types'
import { getElementPlusRules, handleBackendValidationErrors, showFieldErrors } from '@/utils/validation'

const router = useRouter()
const authStore = useAuthStore()
const themeStore = useThemeStore()

// 检查是否在Electron环境
const isElectron = computed(() => {
  return !!(window as any).electronAPI
})

// 表单引用
const formRef = ref<FormInstance>()
const captchaRef = ref()

// 表单数据
const form = reactive<LoginRequest>({
  username: '',
  password: '',
  captcha: '',
  captchaId: ''
})

// 记住我
const rememberMe = ref(false)

// 验证码状态
const captchaValid = ref(false)

// 表单验证规则 - 使用统一的验证规则
const validationRules = getElementPlusRules()
const rules: FormRules = {
  ...validationRules.login,
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 4, message: '验证码为4位字符', trigger: 'blur' },
    {
      validator: (_rule: any, value: string, callback: Function) => {
        if (!captchaRef.value?.validate()) {
          callback(new Error('验证码错误'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 处理验证码变化
const handleCaptchaChange = (value: string, isValid: boolean) => {
  captchaValid.value = isValid
  form.captcha = value
}

// 处理验证码ID变化
const handleCaptchaIdChange = (newCaptchaId: string) => {
  form.captchaId = newCaptchaId
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    // 前端验证表单
    await formRef.value.validate()

    // 执行登录
    const success = await authStore.login(form)

    if (success) {
      // 登录成功，等待一下再跳转，确保状态更新完成
      setTimeout(() => {
        router.push('/dashboard')
      }, 100)
    }
  } catch (error: any) {
    console.error('登录失败:', error)

    // 处理后端验证错误
    if (error.response?.status === 400 && error.response?.data?.data) {
      // 后端返回的字段验证错误
      const backendErrors = error.response.data.data
      const validationErrors = handleBackendValidationErrors(backendErrors)

      // 在表单中显示字段级别的错误
      showFieldErrors(formRef.value, validationErrors)

      // 显示总体错误提示
      ElMessage.error('请检查输入信息')
    } else if (error.response?.data?.message) {
      // 显示后端返回的具体错误信息
      ElMessage.error(error.response.data.message)
    } else {
      // 显示通用错误信息
      ElMessage.error('登录失败，请重试')
    }

    // 登录失败时刷新验证码
    captchaRef.value?.refresh()
  }
}

// 组件挂载时的初始化（验证码ID由CaptchaCode组件管理）
onMounted(() => {
  // 验证码相关初始化由CaptchaCode组件处理
})
</script>

<style lang="scss" scoped>
// ==================== 主容器 ====================
.auth-container {
  position: relative;
  min-height: 100vh;
  display: flex;
  flex-direction: column; // 改为垂直布局，标题栏在顶部，内容在下方
  overflow-x: hidden;
  overflow-y: auto;
}

// ==================== 背景装饰 ====================
.auth-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 0;

  .bg-pattern {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image:
      radial-gradient(circle at 25% 25%, var(--theme-primary-bg) 0%, transparent 50%),
      radial-gradient(circle at 75% 75%, var(--theme-primary-bg) 0%, transparent 50%);
    opacity: 0.3;
  }

  .bg-gradient {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(
      135deg,
      var(--bg-color-primary) 0%,
      var(--bg-color-secondary) 100%
    );
  }
}

// ==================== 内容区域 ====================
.auth-content {
  position: relative;
  z-index: 1;
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 80px;
  align-items: center;
  flex: 1; // 占据剩余空间
  min-height: 0; // 允许flex收缩

  @media (max-width: 1024px) {
    grid-template-columns: 1fr;
    gap: 40px;
    max-width: 480px;
  }

  @media (max-width: 768px) {
    padding: 16px;
    gap: 32px;
  }
}

// ==================== 品牌展示区 ====================
.brand-section {
  display: flex;
  flex-direction: column;
  justify-content: center;

  @media (max-width: 1024px) {
    text-align: center;
    order: 2;
  }
}

.brand-content {
  .brand-logo {
    display: flex;
    align-items: center;
    margin-bottom: 32px;

    @media (max-width: 1024px) {
      justify-content: center;
    }

    .logo-icon {
      font-size: 48px;
      color: var(--theme-primary);
      margin-right: 16px;
    }

    .logo-text {
      font-size: 36px;
      font-weight: 700;
      color: var(--text-color-primary);
      margin: 0;
      background: linear-gradient(135deg, var(--theme-primary), var(--theme-primary-light));
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
    }
  }

  .brand-description {
    h2 {
      font-size: 28px;
      font-weight: 600;
      color: var(--text-color-primary);
      margin: 0 0 16px 0;
      line-height: 1.3;

      @media (max-width: 768px) {
        font-size: 24px;
      }
    }

    p {
      font-size: 16px;
      color: var(--text-color-secondary);
      line-height: 1.6;
      margin: 0 0 32px 0;
    }
  }

  .feature-highlights {
    display: flex;
    gap: 24px;

    @media (max-width: 1024px) {
      justify-content: center;
    }

    @media (max-width: 768px) {
      flex-direction: column;
      gap: 16px;
    }

    .feature-item {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 12px 16px;
      background-color: var(--bg-color-tertiary);
      border-radius: 8px;
      border: 1px solid var(--border-color-light);
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: var(--shadow-base);
      }

      .el-icon {
        font-size: 18px;
        color: var(--theme-primary);
      }

      span {
        font-size: 14px;
        font-weight: 500;
        color: var(--text-color-secondary);
      }
    }
  }
}

// ==================== 表单区域 ====================
.form-section {
  display: flex;
  justify-content: center;

  @media (max-width: 1024px) {
    order: 1;
  }
}

.form-container {
  position: relative;
  width: 100%;
  max-width: 420px;
  padding: 40px;
  border-radius: 16px;
  backdrop-filter: blur(10px);

  @media (max-width: 768px) {
    padding: 32px 24px;
    border-radius: 12px;
  }
}

// ==================== 主题切换按钮 ====================
.theme-toggle {
  position: absolute;
  top: 16px;
  right: 16px;

  .theme-toggle-btn {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: var(--bg-color-secondary);
    border: 1px solid var(--border-color-light);
    transition: all 0.3s ease;

    &:hover {
      background-color: var(--theme-primary-bg);
      border-color: var(--theme-primary);
      transform: scale(1.05);
    }

    .el-icon {
      font-size: 18px;
      color: var(--theme-primary);
    }
  }
}

// ==================== 表单头部 ====================
.form-header {
  text-align: center;
  margin-bottom: 5px;

  h2 {
    font-size: 28px;
    font-weight: 600;
    color: var(--text-color-primary);
    margin: 0 0 8px 0;
  }

  p {
    font-size: 16px;
    color: var(--text-color-secondary);
    margin: 0;
    line-height: 1.5;
  }
}

// ==================== 表单样式 ====================
.auth-form {
  .input-wrapper {
    margin-bottom: 5px;
    position: relative;

    .input-label {
      display: block;
      font-size: 14px;
      font-weight: 500;
      color: var(--text-color-primary);
      margin-bottom: 8px;
    }

    .input-help {
      margin-top: 4px;

      .el-text {
        color: var(--el-text-color-placeholder);
        font-size: 12px;
        line-height: 1.4;
      }
    }
  }

  .form-options {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 32px;

    .remember-checkbox {
      :deep(.el-checkbox__label) {
        color: var(--text-color-secondary);
        font-size: 14px;
      }
    }

    .forgot-link {
      font-size: 14px;
      font-weight: 500;
    }
  }

  .submit-btn {
    width: 100%;
    height: 48px;
    font-size: 16px;
    font-weight: 600;
    border-radius: 8px;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-1px);
      box-shadow: var(--theme-primary-shadow);
    }

    .el-icon {
      margin-right: 8px;
    }
  }
}

// ==================== 表单底部 ====================
.form-footer {
  margin-top: 32px;
  text-align: center;

  .divider {
    position: relative;
    margin: 0px 0;

    &::before {
      content: '';
      position: absolute;
      top: 50%;
      left: 0;
      right: 0;
      height: 1px;
      background-color: var(--border-color-light);
    }

    span {
      position: relative;
      background-color: var(--bg-color-tertiary);
      padding: 0 16px;
      font-size: 14px;
      color: var(--text-color-tertiary);
    }
  }

  .register-prompt {
    font-size: 14px;
    color: var(--text-color-secondary);
    margin: 0;

    .register-link {
      font-weight: 600;
      text-decoration: none;
      margin-left: 4px;

      &:hover {
        text-decoration: underline;
      }
    }
  }
}

// ==================== 深度样式覆盖 ====================
:deep(.el-form-item) {
  margin-bottom: 0;
  position: relative;

  .el-form-item__content {
    position: relative;
  }

  .el-form-item__error {
    position: static !important;
    display: block !important;
    width: 100% !important;
    color: var(--color-danger) !important;
    font-size: 12px !important;
    margin-top: 2px !important;
    margin-left: 0 !important;
    line-height: 1.4 !important;
    text-align: left !important;
  }
}

:deep(.el-input) {
  .el-input__wrapper {
    background-color: var(--bg-color-tertiary);
    border: 1px solid var(--border-color-light);
    border-radius: 8px;
    padding: 12px 16px;
    transition: all 0.3s ease;
    box-shadow: none;

    &:hover {
      border-color: var(--theme-primary);
    }

    &.is-focus {
      border-color: var(--theme-primary);
      box-shadow: 0 0 0 3px var(--theme-primary-bg);
    }

    &.is-error {
      border-color: var(--color-danger);

      &.is-focus {
        box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.1);
      }
    }
  }

  .el-input__inner {
    height: auto;
    line-height: 1.5;
    color: var(--text-color-primary);
    font-size: 14px;

    &::placeholder {
      color: var(--text-color-tertiary);
    }
  }

  .el-input__prefix {
    color: var(--text-color-tertiary);
  }

  .el-input__suffix {
    color: var(--text-color-tertiary);
  }
}

:deep(.el-checkbox) {
  .el-checkbox__input {
    .el-checkbox__inner {
      background-color: var(--bg-color-tertiary);
      border-color: var(--border-color-base);

      &:hover {
        border-color: var(--theme-primary);
      }
    }

    &.is-checked .el-checkbox__inner {
      background-color: var(--theme-primary);
      border-color: var(--theme-primary);
    }
  }

  .el-checkbox__label {
    color: var(--text-color-secondary);
    font-size: 14px;
    line-height: 1.5;
  }
}

:deep(.el-button) {
  &.is-loading {
    .el-icon {
      margin-right: 0;
    }
  }
}

// ==================== 响应式优化 ====================
@media (max-width: 480px) {
  .auth-content {
    padding: 12px;
  }

  .form-container {
    padding: 24px 20px;
  }

  .brand-content {
    .brand-logo {
      .logo-icon {
        font-size: 40px;
      }

      .logo-text {
        font-size: 28px;
      }
    }

    .brand-description h2 {
      font-size: 20px;
    }

    .feature-highlights {
      .feature-item {
        padding: 8px 12px;

        span {
          font-size: 12px;
        }
      }
    }
  }

  .form-header h2 {
    font-size: 24px;
  }
}
</style>
